package com.starblink.android.basic.network.interceptor

import com.apollographql.apollo3.api.http.HttpRequest
import com.apollographql.apollo3.api.http.HttpResponse
import com.apollographql.apollo3.network.http.HttpInterceptor
import com.apollographql.apollo3.network.http.HttpInterceptorChain
import com.starblink.android.basic.network.config.HeadsHandle
import kotlinx.coroutines.sync.Mutex

class AuthorizationInterceptor() : HttpInterceptor {
    private val mutex = Mutex()

    override suspend fun intercept(
        request: HttpRequest,
        chain: HttpInterceptorChain
    ): HttpResponse {
        //https://www.jianshu.com/p/8170cdceaf38
        //https://www.apollographql.com/docs/kotlin/advanced/authentication
        val response = chain.proceed(
            request.newBuilder().build()
        )
        return if (response.statusCode == 401) {
            chain.proceed(
                request.newBuilder()
                    .addHeaders(HeadsHandle.getHttpDfHeads(true)).build()
            )
        } else {
            response
        }
    }
}